package cn.wowjoy.office.common.widget.keyborad;

import android.content.Context;
import android.graphics.drawable.Drawable;
import android.inputmethodservice.Keyboard;
import android.inputmethodservice.KeyboardView;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import java.math.BigDecimal;
import java.text.DecimalFormat;

import cn.wowjoy.office.R;


public abstract class CustomBaseKeyboard extends Keyboard implements KeyboardView.OnKeyboardActionListener {

    protected EditText etCurrent;
    protected TextView tvCurrent;
    protected View nextFocusView;
    protected CustomKeyStyle customKeyStyle;
    protected Context mContext;
    protected StringBuilder mString;
    protected boolean isFirstKeyAfterShow;


    public CustomBaseKeyboard(Context context, int xmlLayoutResId) {
        super(context, xmlLayoutResId);
        this.mContext = context;
    }

    public CustomBaseKeyboard(Context context, int xmlLayoutResId, int modeId, int width, int height) {
        super(context, xmlLayoutResId, modeId, width, height);
        this.mContext = context;
    }

    public CustomBaseKeyboard(Context context, int xmlLayoutResId, int modeId) {
        super(context, xmlLayoutResId, modeId);
        this.mContext = context;
    }

    public CustomBaseKeyboard(Context context, int layoutTemplateResId, CharSequence characters, int columns, int horizontalPadding) {
        super(context, layoutTemplateResId, characters, columns, horizontalPadding);
        this.mContext = context;
    }

    protected int getKeyCode(int resId) {
        if (null != etCurrent) {
            return etCurrent.getResources().getInteger(resId);
        } else {
            return Integer.MIN_VALUE;
        }
    }

    public TextView getTvCurrent() {
        return tvCurrent;
    }

    public void setTvCurrent(TextView tvCurrent) {
        this.tvCurrent = tvCurrent;
        initStringBuilder(tvCurrent);
    }

    public void setCurEditText(EditText etCurrent) {
        this.etCurrent = etCurrent;


    }

    private void initStringBuilder(TextView tvCurrent){
        isFirstKeyAfterShow = true;
        String s = tvCurrent.getText().toString().trim();
        mString = new StringBuilder();
        if (!TextUtils.isEmpty(s) && s.contains(".")){
            int length = s.length();
            if (TextUtils.equals("00",s.substring(length - 2, length))){
                mString.append(s.substring(0, length - 3));
            } else {
                if (TextUtils.equals("0",s.substring(length - 1, length))){
                    mString.append(s.substring(0, length - 1));
                } else {
                    mString.append(s);
                }
            }
        }

    }
    public EditText getCurEditText() {
        return etCurrent;
    }

    public void setNextFocusView(View view) {
        this.nextFocusView = view;
    }

    public CustomKeyStyle getCustomKeyStyle() {
        return customKeyStyle;
    }

    public void setCustomKeyStyle(CustomKeyStyle customKeyStyle) {
        this.customKeyStyle = customKeyStyle;
    }

    @Override
    public void onPress(int primaryCode) {

    }

    @Override
    public void onRelease(int primaryCode) {

    }


    private String formatString(StringBuilder sb){
        String s = "0";
        if (sb.length() > 0) {
            if (sb.toString().trim().equals("-")) {
                return sb.toString().trim();
            } else {
                s = sb.toString().trim();
            }
        }
        BigDecimal bd = new BigDecimal(s);
        DecimalFormat df = new DecimalFormat("#############0.00");//小数点点不够两位补0，例如："0" --> 0.00（个位数补成0因为传入的是0则会显示成：.00，所以各位也补0；）
        String xs = df.format(bd.setScale(2, BigDecimal.ROUND_DOWN));
        return xs;
    }

    private StringBuilder formatSb(StringBuilder sb){
        if (sb.toString().contains(".")){
            if (sb.toString().contains("-")){
                if (sb.indexOf(".") > 15){
                    sb.delete(15,sb.indexOf("."));
                }

                if (sb.length() > 18){
                    sb.delete(18,sb.length());
                }
            } else {
//                if (sb.indexOf(".") > 14){
//                    sb.delete(14,sb.indexOf("."));
//                }

                if (sb.length() > 17){
                    sb.delete(17,sb.length());
                }
            }

        } else if (sb.toString().contains("-")){
           if (sb.length() > 15){
               sb.delete(15,sb.length());
           }
        } else {
            if (sb.length() > 16){
                sb.delete(16,sb.length());
            }
        }
        return sb;
    }
    @Override
    public void onKey(int primaryCode, int[] keyCodes) {
        if (null != mString && null != etCurrent && etCurrent.hasFocus() && !handleSpecialKey(etCurrent, primaryCode) ) {
            int start = mString.length();
            if (primaryCode == Keyboard.KEYCODE_DELETE) { //回退
                if (!TextUtils.isEmpty(mString)) {
                    if (start >= 0) {
                        mString.deleteCharAt(start - 1);
                    }
                }
            } else if (primaryCode == getKeyCode(R.integer.keycode_empty_text)) { //清空
                mString.delete(0,start);
            } else if (primaryCode == getKeyCode(R.integer.keycode_hide_keyboard)) { //隐藏
                hideKeyboard();
            } else if (primaryCode == getKeyCode(R.integer.keycode_cur_price)){
                hideKeyboard();
                //显示当前String
            } else if (primaryCode == 46) { //小数点
                if (!mString.toString().contains(".")) {
                    if (isFirstKeyAfterShow){
                        if (!TextUtils.isEmpty(mString))
                            mString.delete(0,start);
                        mString.append("0"+Character.toString((char) primaryCode));
                    } else {
                        mString.insert(start, Character.toString((char) primaryCode));
                    }
                }
            } else if (primaryCode == 45){ //减号
                if (!TextUtils.isEmpty(mString)) {
                    if (isFirstKeyAfterShow){
                        mString.delete(0,start);
                        mString.append(Character.toString((char) primaryCode).trim());
                    }

                } else {
                    mString.append(Character.toString((char) primaryCode).trim());
                }
//                if (!mString.toString().contains("-")) {
//                    if (isFirstKeyAfterShow){
//                        if (!TextUtils.isEmpty(mString))
//                            mString.delete(0,start);
//                        mString.append("0"+Character.toString((char) primaryCode));
//                    } else if (start == 0){
//                        mString.insert(start, Character.toString((char) primaryCode));
//                    }
//                }
            }
            else { //其他默认
                if(!TextUtils.isEmpty(mString.toString().trim()) && mString.toString().contains(".")){
                    if(mString.toString().substring(mString.toString().indexOf(".")+1,mString.toString().length()).length() > 2){
                        return;
                    }
                }
                if (isFirstKeyAfterShow){
                    mString.delete(0,start);
                    mString.append(Character.toString((char) primaryCode));
                } else {
                    mString.insert(start, Character.toString((char) primaryCode));
                }
            }
        }
        mString = formatSb(mString);
        if (null != onTextChangeListener)
            onTextChangeListener.onChange(mString);
        tvCurrent.setText(formatString(mString));
        if (isFirstKeyAfterShow)
            isFirstKeyAfterShow = false;
        //getKeyboardView().postInvalidate();
    }


    public interface OnTextChangeListener{
        void onChange(StringBuilder sb);
    }
    private OnTextChangeListener onTextChangeListener;

    public void setOnTextChangeListener(OnTextChangeListener onTextChangeListener) {
        this.onTextChangeListener = onTextChangeListener;
    }

    public void hideKeyboard() {
        //hideSoftKeyboard(etCurrent);
        if (null != nextFocusView) nextFocusView.requestFocus();
//        etCurrent.clearFocus();

    }

    /**
     * 处理自定义键盘的特殊定制键
     * 注: 所有的操作要针对etCurrent来操作
     *
     * @param etCurrent   当前操作的EditText
     * @param primaryCode 选择的Key
     * @return true: 已经处理过, false: 没有被处理
     */
    public abstract boolean handleSpecialKey(EditText etCurrent, int primaryCode);

    @Override
    public void onText(CharSequence text) {

    }

    @Override
    public void swipeLeft() {

    }

    @Override
    public void swipeRight() {

    }

    @Override
    public void swipeDown() {

    }

    @Override
    public void swipeUp() {

    }

    public interface CustomKeyStyle {
        Drawable getKeyBackground(Key key, TextView etCur);

        Float getKeyTextSize(Key key, TextView etCur);

        Integer getKeyTextColor(Key key, TextView etCur);

        CharSequence getKeyLabel(Key key, TextView etCur);
    }

    public static class SimpleCustomKeyStyle implements CustomKeyStyle {

        @Override
        public Drawable getKeyBackground(Key key, TextView etCur) {
            return key.iconPreview;
        }

        @Override
        public Float getKeyTextSize(Key key, TextView etCur) {
            return null;
        }

        @Override
        public Integer getKeyTextColor(Key key, TextView etCur) {
            return null;
        }

        @Override
        public CharSequence getKeyLabel(Key key, TextView etCur) {
            return key.label;
        }

        protected int getKeyCode(Context context, int resId) {
            if (null != context) {
                return context.getResources().getInteger(resId);
            } else {
                return Integer.MIN_VALUE;
            }
        }

        protected Drawable getDrawable(Context context, int resId) {
            if (null != context) {
                return context.getResources().getDrawable(resId);
            }
            return null;
        }
    }
}